package utils

import (
	"bytes"
	"os/exec"
	"strings"
)

// WinBat 对应Java中的WinBat
type WinBat struct {
	originalCommandMsg []string
	outputs            []string
	exitValues         []int
}

// GetInstance 创建新的WinBat实例
func (w *WinBat) GetInstance() *WinBat {
	return &WinBat{}
}

// GetIntegrationOutput 获取所有命令的整合输出
func (w *WinBat) GetIntegrationOutput() (string, error) {
	if len(w.originalCommandMsg) == 0 {
		return "", nil
	}
	var result strings.Builder
	for i, output := range w.outputs {
		if i > 0 {
			result.WriteString("\n\n")
		}
		result.WriteString(output)
	}
	return result.String(), nil
}

// GetIntegrationCommand 获取所有命令的整合字符串
func (w *WinBat) GetIntegrationCommand() (string, error) {
	if len(w.originalCommandMsg) == 0 {
		return "", nil
	}
	return strings.Join(w.originalCommandMsg, "\n"), nil
}

// GetOriginalCommand 获取原始命令数组
func (w *WinBat) GetOriginalCommand() ([]string, error) {
	if len(w.originalCommandMsg) == 0 {
		return nil, nil
	}
	return w.originalCommandMsg, nil
}

// GetExitValues 获取所有命令的退出码
func (w *WinBat) GetExitValues() ([]int, error) {
	if len(w.originalCommandMsg) == 0 {
		return nil, nil
	}
	return w.exitValues, nil
}

// GetLastExitValues 获取最后一个命令的退出码
func (w *WinBat) GetLastExitValues() (int, error) {
	if len(w.originalCommandMsg) == 0 {
		return 0, nil
	}
	return w.exitValues[len(w.exitValues)-1], nil
}

// Execute 执行多个命令
func (w *WinBat) Execute(commands []string) (*WinBat, error) {
	w.originalCommandMsg = commands
	w.outputs = make([]string, len(commands))
	w.exitValues = make([]int, len(commands))

	for i, command := range commands {
		cmd := exec.Command("cmd", "/C", command)
		var out bytes.Buffer
		cmd.Stdout = &out
		err := cmd.Run()
		if err != nil {
			if exitError, ok := err.(*exec.ExitError); ok {
				w.exitValues[i] = exitError.ExitCode()
			}
			return w, err
		}
		w.outputs[i] = strings.TrimSpace(out.String())
		w.exitValues[i] = 0
	}
	return w, nil
}
